package com.duan.nowcoder.community.controller;

import com.duan.nowcoder.community.annotation.LoginRequired;
import com.duan.nowcoder.community.entity.*;
import com.duan.nowcoder.community.event.EventProducer;
import com.duan.nowcoder.community.service.CommentService;
import com.duan.nowcoder.community.service.DiscussPostService;
import com.duan.nowcoder.community.service.LikeService;
import com.duan.nowcoder.community.service.UserService;
import com.duan.nowcoder.community.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "您还未登录！");
        }

        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);

        Event event = new Event()
                .setUserId(user.getId())
                .setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());
        eventProducer.fireEvent(event);

        //加入Redis重算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisUtil.sSet(redisKey,discussPost.getId());

        return CommunityUtil.getJSONString(0, "发布成功！");
    }

    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPost(@PathVariable("discussPostId") int postId, Model model, Page page) {
        //帖子
        DiscussPost post = discussPostService.findDiscussPostById(postId);
        model.addAttribute("post", post);
        //作者
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);
        //是否已赞
        if (hostHolder.getUser() != null) {
            model.addAttribute("isLike", likeService.isEntityLike(hostHolder.getUser().getId(), ENTITY_TYPE_POST, postId));
        } else {
            model.addAttribute("isLike", 0);
        }
        //获赞数量
        model.addAttribute("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId));
        //评论的分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + postId);
        page.setRows(post.getCommentCount());
        //评论列表
        List<Comment> commentList = commentService.findCommentEntity(ENTITY_TYPE_POST, postId, page.getOffset(), page.getLimit());
        //评论Vo列表
        ArrayList<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                //评论VO
                Map<String, Object> commentVo = new HashMap<>();
                //评论
                commentVo.put("comment", comment);
                //作者
                commentVo.put("user", userService.findUserById(comment.getUserId()));
                //回复列表
                List<Comment> replyList = commentService.findCommentEntity(ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                //回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        //回复
                        replyVo.put("reply", reply);
                        //作者
                        replyVo.put("user", userService.findUserById(reply.getUserId()));
                        //目标
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        //是否已赞
                        if (hostHolder.getUser() != null) {
                            replyVo.put("isLike", likeService.isEntityLike(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId()));
                        } else {
                            replyVo.put("isLike", 0);
                        }
                        //获得赞数
                        replyVo.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId()));
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);
                //回复数量
                commentVo.put("replyCount", commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId()));
                //是否已赞

                if (hostHolder.getUser() != null) {
                    commentVo.put("isLike", likeService.isEntityLike(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId()));
                } else {
                    commentVo.put("isLike", 0);
                }
                //获得赞数
                commentVo.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId()));
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);
        return "site/discuss-detail";
    }

    @PostMapping("/top")
    @ResponseBody
    public String setPostTop(int postId){
        discussPostService.updatePostType(postId,POST_TYPE_TOP);
        Event event = new Event()
                .setUserId(hostHolder.getUser().getId())
                .setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(postId);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJSONString(0);
    }

    @PostMapping("/wonderful")
    @ResponseBody
    public String setPostWonderful(int postId){
        discussPostService.updatePostStatus(postId,POST_STATUS_WONDERFUL);
        Event event = new Event()
                .setUserId(hostHolder.getUser().getId())
                .setTopic(TOPIC_PUBLISH)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(postId);
        eventProducer.fireEvent(event);
        //加入Redis重算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisUtil.sSet(redisKey,postId);
        return CommunityUtil.getJSONString(0);
    }

    @PostMapping("/delete")
    @ResponseBody
    public String deletePost(int postId){
        discussPostService.updatePostStatus(postId,POST_STATUS_DELETE);
        Event event = new Event()
                .setUserId(hostHolder.getUser().getId())
                .setTopic(TOPIC_DELETE)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(postId);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJSONString(0);
    }


}
